const send = require("koa-send"); // 处理静态文件
const user = require("../controller/user");
const bundle = require("../../dist/vue-ssr-server-bundle.json");
const clientManifest = require("../../dist/vue-ssr-client-manifest.json");
const renderer = require("vue-server-renderer").createBundleRenderer(bundle, {
  runInNewContext: false, // 推荐
  template: require("fs").readFileSync("index.template.html", "utf-8"),
  clientManifest
});
const path = require("path");

// const article = require("../controller/article");
// const address = require("../controller/address");
// const dict = require("../controller/dict");
// const file = require("../controller/file");
const router = require("koa-router")();
router.post("/api/user/login", user.login);
// router.get("/user", user.getUserById);
// router.get("/user/list", user.getUserList);
// router.post("/user/setAddress", address.setByIp);
//
// router.get("/article/list", article.getList);
// router.post("/article/save", article.save);
// router.post("/article/query", article.query);
//
// router.get("/dict/:parentCode", dict.getChildListByParentCode);
//
// router.post("/file/upload", file.upload);
//
// router.get("/w/article/list", article.getListByWeb);

router.get("*", async ctx => {
  const { request, $isLogin = true } = ctx;
  const context = { url: request.url };
  const url = ctx.path;
  if (url.includes(".")) {
    return await send(ctx, url, {
      root: path.resolve(__dirname, "../../dist")
    });
  }
  if ($isLogin) {
    if (url.includes("/login")) {
      context.url = "/admin";
    }
  } else {
    if (url.includes("/admin")) {
      context.url = "/login";
    }
  }
  ctx.body = await renderToString(context);
});

/**
 * 读取字符串
 * @param context
 * @returns {Promise<unknown>}
 */
function renderToString(context) {
  return new Promise((resolve, reject) => {
    renderer.renderToString(context, (err, html) => {
      const currentHours = new Date().getHours();
      if (currentHours > 7 && currentHours < 16) {
        // 在早上 7 点和晚上 16 点是夜间模式
        html = html.replace(
          "</head>",
          '<style id="custom-style">body { background: #414141; }</style>'
        );
      }
      err ? reject(err) : resolve(html);
    });
  });
}

module.exports = router;
